package edu.mtu.citizenscience.ethnography.uploader;

import org.json.JSONObject;

class EthnographyCallback {

	public static final int STATUS_NORESPONSE = 0;
	public static final int STATUS_OTHER = 1;
	
	private static final int STATUS_OK = 200;
	
	private static boolean isClientError(int status) {
		return status >= 400 && status < 500;
	}
	
	private static boolean isServerError(int status) {
		return status >= 500 && status < 600;
	}
	
	public static final int STATUS_SERVER_BAD_REQUEST = 599;

	private EthnographyResponseHandler handler;

	public EthnographyCallback(EthnographyResponseHandler handler) {
		this.handler = handler;
	}

	/**
	 * Calls the appropriate handler method based on the response code.
	 * @param url The URL the response was sent to
	 * @param json A JSON object containing the response data. May be null unless
	 * status is 200 (OK).
	 * @param status The HTTP status code that was returned in the response, or one of the custom
	 * codes specified in this class.
	 */
	public void callback(String url, JSONObject json, int status) {
		if (status == STATUS_NORESPONSE || status == STATUS_OTHER) {
			handler.onNoResponse(json);
		} else if (status == STATUS_OK) {
			handler.onSuccess(json);
		} else if (isClientError(status)) {
			handler.onFailure(json);
		} else if (isServerError(status)) {
			handler.onError(json);
		}
	}
}
